package org.mm4juser.repository;

import org.mm4juser.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Repository
public interface UserRepository extends JpaRepository<User, Integer> {
	/**
	 * 登陆时加载用户信息
	 *
	 * @return user
	 */
	@Query(nativeQuery = true, value = "select * from tb_user where email = :email and is_deleted = 0")
	User loadUserByEmail(String email);
	
	/**
	 * 通过ID查找用户
	 *
	 * @param id ID
	 */
	@Query(nativeQuery = true, value = "select * from tb_user where id = :id and is_deleted = 0")
	User loadUserById(Integer id);
	
	/**
	 * 通过用户名查找用户
	 *
	 * @param username 用户名
	 */
	@Query(nativeQuery = true, value = "select * from tb_user where username = :username and is_deleted = 0")
	User loadUserByUsername(String username);
	
	/**
	 * 加载全部用户
	 */
	@Query(nativeQuery = true, value = "select * from tb_user where is_deleted = 0")
	List<User> allUsers();
	
	/**
	 * 创建用户
	 *
	 * @param user user实体
	 */
	@Transactional
	@Modifying
	@Query(nativeQuery = true,
	       value = "insert into tb_user (creator, creation_date, modifier, modification_date, is_deleted, version, username, password, email, uuid, avatar, signature, gender, birthday) VALUES (:#{#user.creator},:#{#user.creationDate},:#{#user.modifier},:#{#user.modificationDate},:#{#user.isDeleted},:#{#user.version},:#{#user.username},:#{#user.password},:#{#user.email},:#{#user.uuid},:#{#user.avatar},:#{#user.signature},:#{#user.gender},:#{#user.birthday})")
	Integer createUser(User user);
	
	/**
	 * 修改用户信息
	 *
	 * @param user 用户
	 */
	@Transactional
	@Modifying
	@Query(nativeQuery = true,
	       value = "update tb_user set username = :#{#user.username},email = :#{#user.email},password = :#{#user.password},signature = :#{#user.signature},gender = :#{#user.gender},birthday = :#{#user.birthday},avatar = :#{#user.avatar} where id = :#{#user.id} and is_deleted = 0")
	Integer updateUser(User user);
	
	/**
	 * 更新用户头像的方法 使用事务注解确保操作的原子性 使用Modifying注解表明这是一个修改操作 使用原生SQL查询进行更新
	 *
	 * @param avatar 要更新的头像路径
	 * @param id     用户ID
	 *
	 * @return 受影响的行数
	 */
	@Transactional
	@Modifying
	@Query(nativeQuery = true, value = "update tb_user set avatar = :avatar where email = :email and is_deleted = 0")
	Integer updateUserAvatar(
		@Param("avatar") String avatar,
		@Param("email") String email);
	
	/**
	 * 用户注销
	 *
	 * @param id 用户ID
	 */
	@Transactional
	@Modifying
	@Query(nativeQuery = true,
	       value = "update tb_user set is_deleted = 1 where id = :id and is_deleted = 0")
	Integer deleteUser(Integer id);
}
